#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''eof
name:至少有两个月订单数据且每月至少订烟三次
code:LeastOrderCnt_Check
tableName:
columnName:
groups:准入>烟商
dependencies:BTM
type:常用指标
dataSourceType:在线指标
description:
eof'''

'''
"1.select min(订单日期) as 最早订单日期 from 订单日期,if 最早订单日期>申请日期-89day,THEN Factor=0 
else 统计count(订单编号) as num1 where 申请日期-30day<订单日期=<申请日期
else 统计count(订单编号) as num2 where 申请日期-60day<订单日期=<申请日期-30day
else 统计count(订单编号) as num3 where 申请日期-90day<订单日期=<申请日期-60day
2.if num1>0 and num2>0 and num3>0 THEN Factor=sum(num1,num2,num3) else Factor=0 "

'''

import sys
import pandas as pd
import datetime

reload(sys)
sys.setdefaultencoding('utf-8')


def LeastOrderCnt_Check():
    null_type_list = ['', None, 'null', 'Null', '/', ' ']
    num1 = []
    num2 = []
    # num3 = []
    try:
        BTM_ = BTM['data']
        if Formate(BTM_.get('bbd_dotime')) is not None:
            ApplTime = datetime.datetime.strptime(Formate(BTM_['bbd_dotime']), '%Y%m%d')
            last_year_days_list = [(ApplTime - pd.tseries.offsets.DateOffset(days=i)).strftime('%Y%m%d') \
                                   for i in [60, 30, 0]]
        else:
            last_year_days_list = [(datetime.datetime.now() - pd.tseries.offsets.DateOffset(days=i)).strftime('%Y%m%d') \
                                   for i in [60, 30, 0]]
    except:
        return u'缺失值'
    try:
        if BTM_.has_key('indent') and BTM_['indent'] not in null_type_list \
            and len(BTM_['indent']) >= 1:
            for i in BTM_['indent']:
                if i.has_key('indentDate') and i['indentDate'] not in null_type_list \
                        and i.has_key('indentNum') and i['indentNum'] not in null_type_list \
                        and i.has_key('indentMoney') and i['indentMoney']  not in null_type_list \
                        and isfloat(i['indentMoney']) \
                        and Formate(i['indentDate']) is not None:
                    if Formate(i['indentDate']) > last_year_days_list[0] and Formate(i['indentDate']) <= last_year_days_list[1]:
                        num2.append(i['indentNum'])
                    elif Formate(i['indentDate']) > last_year_days_list[1] and Formate(i['indentDate']) <= last_year_days_list[2]:
                        num1.append(i['indentNum'])
                    else:
                        pass
            if len(num1) >= 3 and len(num2) >= 3:
                num = len(num1) + len(num2)
                return num
            else:
                return 0
        else:
            return u'缺失值'
    except:
        return u'缺失值'
    
def Formate(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                except:
                    date = None
    return date


def isfloat(x):
    try:
        if isinstance(float(x), float) and float(x)>=0:
            return True
        else:
            return False
    except:
        return False


result = LeastOrderCnt_Check()